package com.zhazha.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * @ClassName UserDetailServiceImpl
 * @autor huangpu
 * @DATE 2019/12/22
 **/
@Configuration
public class UserDetailServiceImpl  implements UserDetailsService {

  /*  @Autowired
    private BCryptPasswordEncoder passwordEncoder;*/

    @Autowired
    JdbcTemplate jdbcTemplate;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        List<Map<String,Object>> list = jdbcTemplate.queryForList("SELECT * FROM  `users`  WHERE username = ?",s);
        if(!CollectionUtils.isEmpty(list)){
            if(list.size()>0){
                String password = (String) list.get(0).get("password");
                String pwd ="{bcrypt}"+ new  BCryptPasswordEncoder().encode(password);

                Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>();
                GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("code");

                grantedAuthorities.add(grantedAuthority);
                User user = new User(s,pwd,grantedAuthorities);
                return user;
            }
        }

        return null;
    }
}

    
    